import { query } from '../services/bank';
import { parse } from 'qs';
import { getCurrentMonth } from '../utils/tools';
import * as global from '../global';

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const namespace = 'bank';
export default {
  namespace,
  state: { data: [], loading: true },
  subscriptions:
  {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/' + namespace) {
          let month = getCurrentMonth();
          dispatch({
            type: 'query',
            payload: {
              auth_user: '',
              wid: global.appdata.wid,
              period: month,
              account: '1002'
            }
          });
        }
      });
    }
  },

  effects:
  {
    *query({ payload }, { call, put }) {
      yield put({ type: 'showLoading' });
      const { data } = yield call(query, parse(payload));
      if (data.result == 'success') {
        yield put({
          type: 'querySuccess',
          payload: { data }
        });
      }
    }
  },

  reducers: {
    querySuccess(state, action) {
      return { ...state, ...action.payload, loading: false };
    },
    hideLoading(state) {
      return {...state, loading: false };
    },
    showLoading(state) {
      return {...state, loading: true };
    }
  },
}